package com.dmjj.login.config;

import com.dmjj.common.util.ScanPool;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 王丽凯
 * @Description: TODO
 * @Title: PoolCache
 * @ProjectName dmjj-bigdata
 * @date 2019/3/18
 */
@Component //使spring管理
@EnableScheduling //定时任务注解
public class PoolCache {

    /**
     * @Description: 缓存超时时间
     * @author 王丽凯
     * @date 2019/3/18
     */
    private static Long timeOutSecond = 30 * 1000L;

    public static ConcurrentHashMap<String, ScanPool> cacheMap = new ConcurrentHashMap<String, ScanPool>();

    /**
     * @Description: 通过key值获取scanPool
     * @author 王丽凯
     * @date 2019/3/20
     */
    public static ScanPool getScanPool(String key){
        ScanPool scanPool = null;
        if (!(cacheMap==null || cacheMap.isEmpty())){
            scanPool = cacheMap.get(key);
            Long sysTime = System.currentTimeMillis();
            Long timeDifference = sysTime - scanPool.getCreateTime();
            System.out.println("d当前时间："+sysTime);
            System.out.println("scanpool时间："+scanPool.getCreateTime());
            System.out.println("时间差："+timeDifference);
            if (scanPool!=null&&timeDifference > timeOutSecond){
                cacheMap.remove(key);
                return null;
            }
            return scanPool;
        }
        return null;
    }

    /**
     * @Description: 根据key清除缓存
     * @author 王丽凯
     * @date 2019/3/20
     */
    public static void cleanValue(String key){
        boolean okRemove = !StringUtils.isEmpty(key)&&!(cacheMap==null || cacheMap.isEmpty());
        if (okRemove){
            cacheMap.remove(key);
        }
    }

    @Scheduled(cron = "0 50 23 * * ?")
    public void clean(){
        try {
            if (cacheMap.keySet().size()>0){
                Iterator<String> iterator = cacheMap.keySet().iterator();
                while (iterator.hasNext()){
                    String key = iterator.next();
                    ScanPool pool = cacheMap.get(key);
                    if (System.currentTimeMillis() - pool.getCreateTime() > timeOutSecond){
                        cacheMap.remove(key);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
